package cn.schoolwow.quickdao.module.database.dql.response.flow;

import cn.schoolwow.quickdao.module.database.dql.parent.domain.QueryContext;
import cn.schoolwow.quickdao.module.database.dql.subCondition.domain.SubQueryOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class GetArrayFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QueryContext queryContext = (QueryContext) flowContext.checkData("queryContext");
        JSONArray resultSetArray = (JSONArray) flowContext.getData("resultSetArray");
        if(null==resultSetArray||resultSetArray.isEmpty()){
            flowContext.putData("array", new JSONArray());
            return;
        }
        if(null==queryContext.queryOption.queryTableOption.entity){
            flowContext.putData("array", resultSetArray);
            return;
        }

        JSONArray array = new JSONArray(resultSetArray.size());

        for(int i=0;i<resultSetArray.size();i++){
            JSONObject resultSetObject = resultSetArray.getJSONObject(i);

            JSONObject o = new JSONObject();
            //主表字段
            for(String column:queryContext.queryOption.queryColumnOption.columnList){
                String columnName = queryContext.queryOption.queryTableOption.entity.getColumnNameByFieldName(column);
                String columnLabel = queryContext.queryOption.queryTableOption.tableAliasName+"_"+columnName;
                if(resultSetObject.containsKey(columnLabel)){
                    o.put(columnName, resultSetObject.get(columnLabel));
                    resultSetObject.remove(columnLabel);
                }
            }
            //子表
            for(SubQueryOption subQueryOption:queryContext.queryOption.subQueryOptionList){
                for(String column:subQueryOption.subQueryColumnOption.columnList){
                    String columnName = subQueryOption.subQueryTableOption.entity.getColumnNameByFieldName(column);
                    String columnLabel = subQueryOption.subQueryTableOption.tableAliasName+"_"+columnName;
                    if(resultSetObject.containsKey(columnLabel)){
                        o.put(columnName, resultSetObject.get(columnLabel));
                        resultSetObject.remove(columnLabel);
                    }
                }
            }
            o.putAll(resultSetObject);
            array.add(o);
        }
        flowContext.putData("array", array);
    }

    @Override
    public String name() {
        return "获取Array方法返回列表";
    }

}
